Java Performance by Scott Oaks

Java Performance by Scott Oaks

Author:Scott Oaks
Language: eng
Format: epub
Publisher: O'Reilly Media
Published: 2019-07-31T16:00:00+00:00


Lazy Initialization Runtime Performance

The usual performance penalty for checking whether lazily initialized variables have been initialized may not always exist. Consider this example from the JDK’s ArrayList class. That class maintains an array of the elements it stores, and in older versions of Java, pseudocode for the class looked like this:

public class ArrayList { private Object[] elementData = new Object[16]; int index = 0; public void add(Object o) { ensureCapacity(); elementData[index++] = o; } private void ensureCapacity() { if (index == elementData.length) { ...reallocate array and copy old data in... } } }

A few years ago, this class was changed so that the elementData array is initialized lazily. But because the ensureCapacity() method already needed to check the array size, the common methods of the class didn’t suffer a performance penalty: the code to check for initialization is the same as the code to check whether the array size needs to be increased. The new code uses a static, shared, zero-length array so that performance is the same:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.